package archer.back.utils

import java.io.FileOutputStream
import java.nio.file.{ Files, Path }

import models.CusPoiOperations
import net.scalax.cpoi.api._
import org.apache.poi.ss.usermodel.Workbook

import scala.util.Failure

object PoiUtils {

  /*def render(data: Seq[Map[String, CellData[_]]])(workbook: Workbook)(columns: List[String]): Path = {
    val parentDir = PictureUtils.genExcelPath
    Files.createDirectories(parentDir)
    val excelPath = parentDir.resolve("output.xls")

    val sheet = workbook.createSheet("学生报名信息")
    val nameList = columns
    val nameCellData = nameList.map(name => CellData(Option(name)))
    val dataList = data.map { row => nameList.map { name =>
      row(name)
    } }
    val table = nameCellData +: dataList
    val styleGen = StyleGen(() => workbook.createCellStyle())
    val zipTable = table.zipWithIndex.map { case (row, index) =>
      val eachRow = sheet.createRow(index)
      row.zipWithIndex.map { case (cellData, index) =>
        val poiCell = eachRow.createCell(index)
        poiCell -> cellData
      }
    }.flatten
    zipTable.foldLeft(styleGen) { case (gen, (poiCell, cellData)) =>
      val newGen = gen.getCellStyle(cellData.styleTrans: _*)
      cellData.setValue(poiCell)
      newGen.cellStyle.map { style =>
        poiCell.setCellStyle(style)
      }
      newGen.styleGen
    }
    workbook.write(new FileOutputStream(excelPath.toFile))
    excelPath
  }*/
  object cusPoiOperations extends CusPoiOperations
  import cusPoiOperations._

  def render(data: Seq[Map[String, CellDataAbs]])(outPutPath: Path)(
    workbook: Workbook)(sheetName: String)(columns: List[String]): Boolean = {
    Files.createDirectories(outPutPath.getParent)
    val sheet = workbook.createSheet(sheetName)
    val nameList = columns
    val nameCellData = nameList.map(name => CPoi.wrapData(name))
    val dataList = data.map { row =>
      nameList.map { name =>
        row.get(name).getOrElse(CPoi.wrapData(Option.empty[String]))
      }
    }
    val table = nameCellData +: dataList
    val zipTable = table.zipWithIndex.map {
      case (row, index) =>
        val eachRow = sheet.createRow(index)
        row.zipWithIndex.map {
          case (cellData, index) =>
            val poiCell = eachRow.createCell(index)
            poiCell -> cellData
        }
    }.flatten
    CPoi.multiplySet(CPoi.newStyleGen, zipTable.toStream) match {
      case Failure(e) =>
        throw e
      case _ =>
    }
    /*zipTable.foldLeft(styleGen) {
      case (gen, (poiCell, cellData)) =>
        val newGen = gen.getCellStyle(cellData.styleTrans: _*)
        cellData.setValue(poiCell)
        newGen.cellStyle.map { style =>
          poiCell.setCellStyle(style)
        }
        newGen.styleGen
    }*/
    workbook.write(new FileOutputStream(outPutPath.toFile))
    true
  }

}
